package com.gome.bg.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.faces.application.Application;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.danga.MemCached.MemCachedClient;
import com.gome.bg.service.LoginService;
import com.gome.bg.util.MySessionContext;
import com.gome.util.TraceInfo;
import javax.servlet.http.Cookie;


@Controller
@RequestMapping("login.do")
public class RbBgController {
	
	@Autowired
 	private LoginService loginService;
	
	@Autowired
	private MemCachedClient memcachedClient;

	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	
	
	public MemCachedClient getMemcachedClient() {
		return memcachedClient;
	}

	public void setMemcachedClient(MemCachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	private MySessionContext myc = MySessionContext.getInstance();
	
	@RequestMapping(params = "method=loginSingle")
	@ResponseBody
	public void loginSingle(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		request.setCharacterEncoding("UTF-8");
		
		session.setMaxInactiveInterval(60*1000*24);
		
		Cookie[] cookies =request.getCookies();
		for(Cookie cookie : cookies){
		    cookie.getName();// get the cookie name
		    cookie.getValue(); // get the cookie value
		    TraceInfo.trace(RbBgController.class).info("name  = "+cookie.getName());
		    TraceInfo.trace(RbBgController.class).info("value = "+cookie.getValue());
		}
		
	
	
		
		Object user = request.getParameter("user");
		Object psw = request.getParameter("psw");
		
		Cookie cookie = new Cookie((String)user,(String)psw);
		//生存周期默认时间为秒，如果设置为负值的话，则为浏览器进程Cookie(内存中保存)，关闭浏览器就失效。
		cookie.setMaxAge(36000);
		//设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
		cookie.setPath("/");
//		cookie.setDomain(".zl.org") ;
		
		
		
		
		
//		String flagStr = "false";
//    	String session_id = session.getId();
//    	TraceInfo.traceInfo(RbBgController.class, session);
//    	TraceInfo.traceInfo(RbBgController.class, "session_id="+session_id);
//        HttpSession sess =(HttpSession) memcachedClient.get(session_id);
//    	TraceInfo.traceInfo(RbBgController.class, "sess="+sess);
//        String username = null;
//        try{
//        	username = (String)session.getAttribute(session_id);
//        }catch(Exception e){
//        	TraceInfo.traceError(RbBgController.class, e);
//        }
//        
//        TraceInfo.traceInfo(RbBgController.class, username);
//        	
//        	if(sess==session){
//        		flagStr = "4";
//        	}else{
//        		if(username!=null){
//        			flagStr = "2";
//        		}else{
//        			boolean flag = false;
//        			try {
//						flag = loginService.pswAuthentification(user, psw);
//					} catch (Exception e) {
//						flag = false;
//					}
//        			TraceInfo.traceInfo(RbBgController.class, "flag="+flag);
//					flag = true;
//					if (flag) {
//						  session.setAttribute(session_id, user);
//						  memcachedClient.add(session_id, session);
//						  HttpSession sessd =(HttpSession) memcachedClient.get(session_id);
//						  TraceInfo.traceInfo(RbBgController.class, "sessdm="+(HttpSession) memcachedClient.get(session_id));
//						  TraceInfo.traceInfo(RbBgController.class, "sessd="+sessd);
//						  flagStr = "1";
//					}
//        		}        		
//       
//        	}
//        
        
     
       TraceInfo.traceInfo(RbBgController.class, "-------------------------------------------------------------------------------------------");
		
		session.setMaxInactiveInterval(100);
		String flagStr = "false";
		String session_id = session.getId();
		HttpSession sess = myc.getSession(session_id);
		if (user == null) {
			flagStr = "3";
		} else {
			if (session == sess) {
				flagStr = "4";
			} else {
				if (myc.iteratesUseSession((String) user)) {
					flagStr = "2";
				} else {
					boolean flag = false;
					try {
						flag = loginService.pswAuthentification(user, psw);
					} catch (Exception e) {
						flag = false;
					}
					flag = true;
					if (flag) {
						myc.AddSession(session);
						myc.AddUserSession(session, (String) user);
						flagStr = "1";
					}

				}
			}
		}
        response.addCookie(cookie);
		response.getWriter().print(flagStr);
		
		
	}
	
	
	@RequestMapping(params = "method=ResUser")
	@ResponseBody
	public void ResUser(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String session_id = session.getId();
		String userName =null;
		try{
			userName= (String) session.getAttribute(session_id);
		}catch(Exception e){
			TraceInfo.traceError(RbBgController.class, e);
		}
		if(userName==null){
			response.getWriter().print("1");
		}
		
//		String session_id = session.getId();
//		HttpSession sess = myc.getSession(session_id);
//		String userName = myc.getUseSession(session_id);
//		if(userName==null){
//			response.getWriter().print("1");
//		}
		response.getWriter().print(userName);
	}

	@RequestMapping(params = "method=monitor")
	public ModelAndView MonitorJsp(HttpServletRequest request, HttpServletResponse response) {

		// String mes = "Hello world !";
		// Map<String, Object> mode = new HashMap<String, Object>();
		// mode.put("1", "mes");
		// mode.put("2", "erwrqw");
		// mode.put("3", "341234");
		// mode.put("4", "5rgrgv");
		//
		/*
		 * <c:forEach var="item" items="${mode}"> ${item.key} > ${item.value}
		 * <br> </c:forEach>
		 */
		TraceInfo.traceInfo();
		String[] mode = new String[10];
		mode[0] = "1234";
		mode[1] = "5678";
		mode[2] = "9012";
		mode[3] = "3456";
		return new ModelAndView("monitor", "mode", mode);
	}

	@ResponseBody
	@RequestMapping(params = "method=loginOut")
	public void loginOut(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		HttpSession sess = myc.getSession(session.getId());
		//HttpSession sess =(HttpSession) memcachedClient.get(session.getId());
		if (sess == null) {
			response.getWriter().print("2");
		}
		myc.DelSession(session);
		myc.DelUseSession(session);
		response.getWriter().print("1");
	}
	
	@ResponseBody
	@RequestMapping(params = "method=extjs")
	public void Extjs(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		Object user = request.getParameter("id");
		TraceInfo.traceInfo(user);
		
		Map map = new HashMap();
		map.put("id", "007");
		map.put("name", "张三");
		map.put("brithday", "2001-01-01");
		map.put("height", "178");
		map.put("sex", "male");
		map.put("discribe", "a good man!");
		JSONArray jsonArray = JSONArray.fromObject(map);
		response.setContentType("text/html;charset=UTF-8");
		try {
			response.getWriter().print(jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.getWriter().print(jsonArray);
		map.clear();
	}
	
	
	
}
